package hn.cch.spring.aop.proxy.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * 模拟JDK动态代理实现
 */
public class JdkDynamicProxy extends Proxy implements DynamicProxyApi {

    static Method method;

    static {
        try {
            method = DynamicProxyApi.class.getMethod("method", String.class);
        } catch (NoSuchMethodException e) {
            throw new NoSuchMethodError(e.getMessage());
        }
    }

    protected JdkDynamicProxy(InvocationHandler h) {
        super(h);
    }

    @Override
    public String method(String string) {
        try {
            return (String) h.invoke(this, method, new Object[]{string});
        } catch (RuntimeException | Error e) {
            throw e;
        } catch (Throwable e) {
            throw new UndeclaredThrowableException(e);
        }
    }
}
